package threadLearn;

/**
 * 同时访问同步方法和非同步方法
 * @author 12609
 *
 */
public class SynchronizedDemo implements Runnable{

	static SynchronizedDemo instance  = new SynchronizedDemo();
	
	@Override
	public void run() {

		if(Thread.currentThread().getName().equals("Thread-0")) {
			method1();
		}else {
			method2();
		}
	}
	
	
	
	private void method1() {
		System.out.println("没加锁 开始 " + Thread.currentThread().getName());
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("" + Thread.currentThread().getName() + " 运行结束");
		
	}



	private synchronized void method2() {
		System.out.println("加锁 开始 " + Thread.currentThread().getName());
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("" + Thread.currentThread().getName() + " 运行结束");
		
	}



	public static void main(String[] args) {
		Thread t1 = new Thread(instance);
		Thread t2 = new Thread(instance);
		t1.start();
		t2.start();
		while(t1.isAlive() || t2.isAlive()) {
			
		}
		System.out.println("finished...");
	}

}
